package xyz.thetbw.autocode

import xyz.thetbw.autocode.utils.StringCaseUtils
import java.util.*

class DataModel {
    //数据库名称
    lateinit var database: String

    //表名称
    lateinit var table: String

    //数据库备注
    lateinit var tableComment: String

    //数据库字段列表
    lateinit var dataFields: List<DataField>

    //数据库字段
    class DataField {
        lateinit var name: String  //字段名称
        lateinit var type: DataFieldType //字段类型

        var nullable: Boolean = true //是否可以为空
        var comment: String? = null //备注
        var length: Int? = null //字段长度

        val humpName: String   //驼峰转换后的字段
            get() = StringCaseUtils.lineToHump(name)

    }

    //数据库字段类型
    sealed class DataFieldType(
        val sqlTypeStr: String, //sql类型
        val javaTypeStr: String, //java类型
        val javaType: Class<out Any> //java class
    ) {
        object VARCHAR : DataFieldType("VARCHAR", "String", String.javaClass)

        object BIGINT : DataFieldType("BIGINT", "Long", Long.javaClass)

        object INT : DataFieldType("INT", "Integer", Int.javaClass)

        object TEXT : DataFieldType("TEXT", "String", String.javaClass)

        object TINYINT : DataFieldType("TINYINT", "Integer", Int.javaClass)

        object CHAR : DataFieldType("CHAR", "String", String.javaClass)

        object DOUBLE : DataFieldType("DOUBLE", "Double", Double.javaClass)

        object DATE : DataFieldType("DATETIME", "Date", Date::class.java)

        object DECIMAL : DataFieldType("DECIMAL","Double",Double.javaClass)

        companion object {
            //根据sqlType获取对应的类型
            fun getBySqlType(sqlType: String): DataFieldType? {
                val subClass = DataFieldType::class::nestedClasses
                for (clazz in subClass.get()) {
                    if (sqlType.uppercase(Locale.getDefault()) == clazz.simpleName && clazz.objectInstance != null && clazz.objectInstance is DataFieldType)
                        return clazz.objectInstance as DataFieldType
                }
                return null
            }

        }
    }


}